package com.leoman.controller.backend;

import com.leoman.common.DataTableFactory;
import com.leoman.controller.common.CommonController;
import com.leoman.entity.Prompt;
import com.leoman.service.PromptService;
import com.leoman.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 文字提示管理
 * Created by 涂奕恒 on 2016/12/13.
 */
@Controller
@RequestMapping(value = "backend/prompt")
public class PromptController extends CommonController {

    @Autowired
    private PromptService promptService;

    @RequestMapping("index")
    public String index() {
        return "backend/文字提示列表";
    }

    @RequestMapping("/list")
    public void list(HttpServletResponse response,
                     Integer draw,
                     Integer start,
                     Integer length) {
        if (null == start || start == 0) {
            start = 1;
        }
        int pageNum = getPageNum(start, length);
        Page<Prompt> page = promptService.find(pageNum, length);

        Map<String, Object> result = DataTableFactory.fitting(draw, page);
        WebUtil.printJson(response, result);
    }

    /**
     * 新增 or 编辑文字提示信息
     */
    @RequestMapping("/save")
    @ResponseBody
    public Integer save(Integer promptId, Integer type, String content) {
        try {
            return promptService.savePrompt(promptId, type, content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 删除文字提示信息
     *
     * @param promptId 文字提示ID
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Integer delete(Integer promptId) {
        try {
            promptService.deleteById(promptId);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
